<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>HLS清晰度切换测试</title>
    <script src="./hls.js"></script>
</head>
<body>
    <h2>HLS清晰度切换测试</h2>
    <video id="video" controls width="800"></video>
    <div>
        <button onclick="switchQuality('720p.m3u8')">高清 (720p)</button>
        <button onclick="switchQuality('480p.m3u8')">标清 (480p)</button>
        <button onclick="switchQuality('master.m3u8')">自动适应</button>
    </div>
    <div id="status">准备播放...</div>

    <script>
        const video = document.getElementById('video');
        const status = document.getElementById('status');
        let hls = new Hls();
        let currentQuality = 'master.m3u8'; // 记录当前清晰度

        // 初始加载主播放列表
        loadMasterPlaylist();

        function loadMasterPlaylist() {
            hls.loadSource('./master.m3u8');
            hls.attachMedia(video);
            currentQuality = 'master.m3u8';
            status.textContent = '已加载主播放列表，支持自动切换';

            hls.on(Hls.Events.MANIFEST_PARSED, function() {
                console.log('可用的清晰度:', hls.levels);
            });
        }

        function switchQuality(qualityUrl) {
            const currentTime = video.currentTime;
            const isPaused = video.paused;

            // 更新当前清晰度记录
            currentQuality = qualityUrl;
            
            if (qualityUrl === 'master.m3u8') {
                status.textContent = '切换到: 自动适应模式';
                // 切换回主播放列表（自动适应）
                hls.destroy();
                hls = new Hls();
                setupHlsEvents(); // 重新设置事件监听
                loadMasterPlaylist();
            } else {
                // 从文件名提取清晰度信息显示
                const qualityName = getQualityName(qualityUrl);
                status.textContent = `切换到: ${qualityName}`;
                
                // 手动切换到指定清晰度
                hls.destroy();
                hls = new Hls();
                setupHlsEvents(); // 重新设置事件监听
                
                hls.loadSource(qualityUrl);
                hls.attachMedia(video);
                
                hls.on(Hls.Events.MANIFEST_PARSED, function() {
                    console.log('单个清晰度文件加载完成:', qualityUrl);
                });
            }

            // 恢复播放位置
            video.currentTime = currentTime;
            if (!isPaused) {
                video.play().catch(e => console.log('播放失败:', e));
            }
        }

        // 设置HLS事件监听
        function setupHlsEvents() {
            // 监听清晰度切换事件（仅对master播放列表有效）
            hls.on(Hls.Events.LEVEL_SWITCHED, function(event, data) {
                console.log('清晰度切换事件:', data);
                if (hls.levels && hls.levels[data.level]) {
                    const level = hls.levels[data.level];
                    const height = level.height || '未知';
                    status.textContent = `自动切换到: ${height}p`;
                }
            });

            // 监听其他有用的事件
            hls.on(Hls.Events.LEVEL_LOADED, function(event, data) {
                console.log('清晰度加载:', data);
            });

            hls.on(Hls.Events.ERROR, function(event, data) {
                console.error('HLS错误:', data);
                if (data.fatal) {
                    switch(data.type) {
                        case Hls.ErrorTypes.NETWORK_ERROR:
                            status.textContent = '网络错误，尝试重新加载...';
                            hls.startLoad();
                            break;
                        case Hls.ErrorTypes.MEDIA_ERROR:
                            status.textContent = '媒体错误，尝试恢复...';
                            hls.recoverMediaError();
                            break;
                        default:
                            status.textContent = '不可恢复错误，请刷新页面';
                            hls.destroy();
                            break;
                    }
                }
            });
        }

        // 从文件名获取清晰度名称
        function getQualityName(filename) {
            const qualityMap = {
                '720p.m3u8': '高清 (720p)',
                '480p.m3u8': '标清 (480p)',
                '360p.m3u8': '流畅 (360p)',
                '1080p.m3u8': '超清 (1080p)',
                'master.m3u8': '自动适应'
            };
            return qualityMap[filename] || filename;
        }

        // 初始设置事件监听
        setupHlsEvents();

        // 添加视频事件监听
        video.addEventListener('loadedmetadata', function() {
            console.log('视频时长:', video.duration);
        });

        video.addEventListener('timeupdate', function() {
            // 可以在这里更新播放进度等信息
        });

    </script>
</body>
</html>